package com.campus.mapper.Impl;

import com.campus.common.StringUtils;
import com.campus.domain.Dto.UserLoginDto;
import com.campus.domain.Dto.UserRegisterDto;
import com.campus.domain.TSysRole;
import com.campus.domain.Vo.UserSelectVo;
import com.campus.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Repository
@Slf4j
public class UserMapperImpl implements UserMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Long addUser(UserRegisterDto userRegisterDto) {
        String sql = "insert into t_sys_user (login_name,password,gender,birthday,phone,email,status) values (?,?,?,?,?,?,?)";

        if (jdbcTemplate == null) {
            log.error("JdbcTemplate is null in someMethod");
        } else {
            log.info("JdbcTemplate is not null in someMethod");
        }

        //返回自增主键
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, userRegisterDto.getLoginName());
            ps.setString(2, StringUtils.md5Encoder(userRegisterDto.getPassword()));//密码加密
            ps.setString(3, userRegisterDto.getGender());
            ps.setDate(4, new Date(userRegisterDto.getBirthday().getTime()));
            ps.setString(5, userRegisterDto.getPhone());
            ps.setString(6, userRegisterDto.getEmail());
            ps.setString(7,"1" );//刚注册状态都为正常
            return ps;
        }, keyHolder);

        // 获取生成的主键
        return keyHolder.getKey().longValue();
    }

    @Override
    public UserLoginDto selectOne(String loginName, String password) {
        if (jdbcTemplate == null) {
            log.error("JdbcTemplate is null in someMethod");
        } else {
            log.info("JdbcTemplate is not null in someMethod");
        }

        String sql = "SELECT * " +
                "FROM t_sys_user t1 " +
                "LEFT JOIN t_sys_user_role t2 on t1.id = t2.user_id " +
                "LEFT JOIN t_sys_role t3 on t2.role_id = t3.id " +
                "WHERE t1.login_name = ? and t1.password = ? ";

        Object[] args = new Object[]{
                loginName,
                StringUtils.md5Encoder(password)
        };

        //Sql语句打印检查
        log.info("Executing SQL: {}", formatSql(sql, args));

        return jdbcTemplate.query(sql,args,rs -> {
            Map<Long, UserLoginDto> userMap = new HashMap<>() ;
            UserLoginDto user = null ;
            while (rs.next()) {
                if (! userMap.containsKey(rs.getInt(1))) {
                    user = new UserLoginDto()
                            .setId(rs.getLong("user_id"))
                            .setLoginName(rs.getString("login_name"))
                            .setPassword(rs.getString("password"))
                            .setGender(rs.getString("gender"))
                            .setBirthday(rs.getDate("birthday"))
                            .setPhone(rs.getString("phone"))
                            .setEmail(rs.getString("email"))
                            .setStatus(rs.getString("status"));
                    user.setRoles(new ArrayList<TSysRole>()) ;
                    userMap.put(user.getId(), user) ;
                }

                Integer roleId = rs.getInt("role_id");
                if(roleId != null){
                    TSysRole role = new TSysRole();
                    role.setId(rs.getLong("role_id"));
                    role.setName(rs.getString("name"));
                    role.setDescription(rs.getString("description"));
                    user.getRoles().add(role);
                }

            }
            return user ;
        });

    }

    @Override
    public UserSelectVo selectByNameOrId(String loginName, Long id) {
        if (jdbcTemplate == null) {
            log.error("JdbcTemplate is null in someMethod");
        } else {
            log.info("JdbcTemplate is not null in someMethod");
        }


        String sql = "SELECT * " +
                "FROM t_sys_user t1 " +
                "LEFT JOIN t_sys_user_role t2 on t1.id = t2.user_id " +
                "LEFT JOIN t_sys_role t3 on t2.role_id = t3.id " +
                "where 1 = 1 ";

        Object[] objects = new Object[]{};
        //判断为不为空，不为空则加相应条件
        if(loginName != null && !loginName.equals("")){
            sql = sql + "and login_name = ? ";
            objects = StringUtils.add(objects,loginName);
        }
        if(id != null){
            sql = sql + "and t1.id = ? ";
            objects = StringUtils.add(objects,id);
        }
        //都空则返回null
        if((loginName == null || loginName.equals(""))&& id == null){
            return null;
        }

        log.info(" name: {}, id: {}",loginName,id);
        //Sql语句打印检查
        log.info("Executing SQL: {}", formatSql(sql, objects));

        return jdbcTemplate.query(sql,objects,rs -> {
            Map<Long, UserSelectVo> userMap = new HashMap<>() ;
            UserSelectVo user = null ;
            while (rs.next()) {
                if (! userMap.containsKey(rs.getInt(1))) {
                    user = new UserSelectVo()
                            .setId(rs.getLong("user_id"))
                            .setLoginName(rs.getString("login_name"))
                            .setGender(rs.getString("gender"))
                            .setBirthday(rs.getDate("birthday"))
                            .setPhone(rs.getString("phone"))
                            .setEmail(rs.getString("email"))
                            .setStatus(rs.getString("status"));
                    user.setRoles(new ArrayList<TSysRole>()) ;
                    userMap.put(user.getId(), user) ;
                }

                Integer roleId = rs.getInt("role_id");
                if(roleId != null){
                    TSysRole role = new TSysRole();
                    role.setId(rs.getLong("role_id"));
                    role.setName(rs.getString("name"));
                    role.setDescription(rs.getString("description"));
                    user.getRoles().add(role);
                }

            }
            return user ;
        });
    }

    private String formatSql(String sql, Object[] args) {
        for (Object arg : args) {
            sql = sql.replaceFirst("\\?", arg instanceof String ? "'" + arg + "'" : arg.toString());
        }
        return sql;
    }

}
